#!/bin/bash
# Copyright 2025 The ChaosBlade Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# 版本信息生成脚本
# 用于从Git Tag自动提取版本信息并生成Go代码

set -e

# 获取Git信息
GIT_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
BUILD_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC')

# 如果没有Git Tag，尝试从环境变量获取版本
if [ -z "$GIT_TAG" ]; then
    if [ -n "$VERSION" ]; then
        GIT_TAG="$VERSION"
    else
        GIT_TAG="dev"
    fi
fi

# 清理版本号（移除v前缀）
VERSION=${GIT_TAG#v}

# 生成版本信息文件
cat > version/version_info.go << EOF
// Code generated by scripts/version.sh. DO NOT EDIT.

package version

import "time"

var (
	// Ver 版本号
	Ver = "$VERSION"
	
	// GitTag Git标签
	GitTag = "$GIT_TAG"
	
	// GitCommit Git提交哈希
	GitCommit = "$GIT_COMMIT"
	
	// GitBranch Git分支
	GitBranch = "$GIT_BRANCH"
	
	// BuildTime 构建时间
	BuildTime = "$BUILD_TIME"
	
	// BuildTimeParsed 解析后的构建时间
	BuildTimeParsed, _ = time.Parse("2006-01-02 15:04:05 UTC", BuildTime)
)

// GetVersionInfo 获取完整的版本信息
func GetVersionInfo() map[string]string {
	return map[string]string{
		"version":    Ver,
		"gitTag":    GitTag,
		"gitCommit": GitCommit,
		"gitBranch": GitBranch,
		"buildTime": BuildTime,
	}
}

// IsRelease 是否为发布版本
func IsRelease() bool {
	return GitTag != "" && GitTag != "dev"
}

// IsDev 是否为开发版本
func IsDev() bool {
	return !IsRelease()
}
EOF

echo "Generated version info:"
echo "  Version: $VERSION"
echo "  Git Tag: $GIT_TAG"
echo "  Git Commit: $GIT_COMMIT"
echo "  Git Branch: $GIT_BRANCH"
echo "  Build Time: $BUILD_TIME"
echo "  Output: version/version_info.go"
